// Arduino智能电表代码
#include <Arduino.h>

// 定义引脚
const int currentPin = A0;
const int voltagePin = A1;

// 校准参数
const float currentFactor = 185.0; // 对应ACS712 5A模块
const float voltageDivider = 5.0; // 电压分压比

void setup() {
  Serial.begin(9600);
  pinMode(currentPin, INPUT);
  pinMode(voltagePin, INPUT);
}

void loop() {
  // 读取10次样本取平均值，提高精度
  float currentSum = 0;
  float voltageSum = 0;
  
  for (int i = 0; i < 10; i++) {
    // 读取电流传感器值
    int currentValue = analogRead(currentPin);
    float current = (currentValue - 512.0) * 5.0 / 1023.0 / currentFactor;
    currentSum += current;
    
    // 读取电压传感器值
    int voltageValue = analogRead(voltagePin);
    float voltage = voltageValue * 5.0 / 1023.0 * voltageDivider;
    voltageSum += voltage;
    
    delay(10);
  }
  
  // 计算平均值
  float avgCurrent = currentSum / 10.0;
  float avgVoltage = voltageSum / 10.0;
  
  // 计算功率和用电量（假设采样间隔为1秒）
  float power = avgVoltage * avgCurrent;
  float energy = power / 3600.0; // 转换为kWh
  
  // 发送JSON格式数据
  String data = "{";
  data += '"'voltage'"':";
  data += avgVoltage;
  data += ',"'current'"':";
  data += avgCurrent;
  data += ',"'power'"':";
  data += power;
  data += ',"'energy'"':";
  data += energy;
  data += '}';
  
  Serial.println(data);
  delay(1000); // 1秒采样一次
}